package org.apache.maven.plugin;

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;

/**
 * Goal that sets the buildNumber property to the current mercurial changeset.
 * 
 * @goal set-build-number
 * @phase validate
 * @author <a href="mailto:biethb@gmail.com">Bruno Bieth</a>
 */
public class BuildNumberMojo extends AbstractMojo {
	
	/** @parameter expression="${project}" */
	private MavenProject mavenProject;

	public void execute() throws MojoExecutionException {
		String buildNumber = "unavailable";
		String[] hgLogCommand = new String[] { 
				"hg", "log", "-l", "1", "--template", "{node}" };
		
		try {
			Process child = Runtime.getRuntime().exec( hgLogCommand );
			buildNumber = IOUtils.toString( child.getInputStream() );
			getLog().debug( "set buildNumber to " + buildNumber );
		} catch( IOException e ) {
			getLog().warn( "buildNumber set to '" + buildNumber + 
					"', can't execute hg log command.", e );
		}
		
		mavenProject.getProperties().put( "buildNumber", buildNumber );
	}
}
